﻿using System;
using System.IO;
using System.Reflection;
#if(!SILVERLIGHT)
using Microsoft.Win32;
#endif

namespace Odin.Contracts.Data
{
	public class WebServerConfig
	{
		public const string ManufacturerKey = "DoLittle Studios";
		public const string ProductKey = "Odin";
		public const string WebServerPathValue = "WebServerPath";

		private string _physicalPath;

		public WebServerConfig()
		{
			Port = -1;
		}


		public string PhysicalPath
		{
			get
			{
				if (string.IsNullOrEmpty(_physicalPath))
				{
					InitializePhysicalPath();
				}
				return _physicalPath;
			}
			set
			{
				_physicalPath = value;
			}
		}

		public int Port { get; set; }
		public bool LocalWebSite { get; set; }
		public bool KeepServerAlive { get; set; }

		private void InitializePhysicalPath()
		{
#if(!SILVERLIGHT)
			var registryRoot = string.Format("Software\\{0}\\{1}", ManufacturerKey, ProductKey);
			var rootKey = Registry.LocalMachine.OpenSubKey(registryRoot);
			if (null != rootKey)
			{
				_physicalPath = rootKey.GetValue(WebServerPathValue) as string;
			}
			else
			{
				if (LocalWebSite)
				{
					var path = Assembly.GetEntryAssembly().Location;
					var webSitePath = string.Format("{0}\\WebSite");
					if (!Directory.Exists(webSitePath))
					{
						throw new ArgumentException(
							"Application not properly installed - missing WebServerPath value in registry or WebSite directory in directory of runner");
					}
					_physicalPath = webSitePath;
				}
			}
			if( string.IsNullOrEmpty(_physicalPath))
			{
				throw new ArgumentException("WebSite or option for LocalWebSite is not specified");
			}
#endif
		}
	}
}
